'''
Created on 2009-11-1

@author: jazy
test routines for pcap
'''
import struct



import ctypes
#import pcap_constants
import pycap.pycap as pycap
import socket


#test for lookupdev and lookupnet
dev=pycap.lookupdev()
print "dev:",dev
ip=0
mask=0
ip,mask=pycap.lookupnet(dev)
print "ip:",socket.inet_ntoa(struct.pack('I',ip))
print "mask:",socket.inet_ntoa(struct.pack('I',mask))

#test for openlive,compile,setfilter,next
snaplen=10000
promisc=1
to_ms=100000
str="port 80"
handle=pycap.open_live(dev, snaplen, promisc, to_ms)
fp=pycap.compile(handle, str, 0, mask)
print "len of fp:", len(fp)
ret2=pycap.setfilter(handle, fp)
print "datalink type:",pycap.datalink(handle)
packet,header=pycap.next(handle)

#dump the packet
print "packet:",packet
print "packet0:%x" % packet[0]
print "packet1:%x" % packet[1]
print "packet2:%x" % packet[2]
print "packet3:%x" % packet[3]
print "packet4:%x" % packet[4]
print "packet5:%x" % packet[5]
print "packet6:%2x" % packet[6]
print "packet7:%2x" % packet[7]
print "packet8:%2x" % packet[8]
print "packet9:%2x" % packet[9]
print "packet10:%2x" % packet[10]
print "packet11:%2x" % packet[11]
print "len:",header.len
print "cap_len:",header.caplen

#test for callback and dispatch
def process(user,pkthdr,packet):
    print "In callback:"
    print "pkthdr[0:7]:",pkthdr.contents.len
    print "packet6:%2x" % packet[6]
    print "packet7:%2x" % packet[7]
    print "packet8:%2x" % packet[8]
    print "packet9:%2x" % packet[9]
    print "packet10:%2x" % packet[10]
    print "packet11:%2x" % packet[11]

cb=pycap.CALLBACK(process)
pycap.dispatch(handle, 1000, cb, "jazy")

#test for lib_version,statuctostr,perror,get_selectable_fd
print "lib version:",pycap.lib_version()
print "status string:",pycap.statustostr(-3)
print "error string:",pycap.strerror(2)
print "fd:",pycap.get_selectable_fd(handle)
print "fileno:",pycap.fileno(handle)
#test for findalldevs freealldevs
if_list=pycap.findalldevs()


for inter in if_list:
    print "interface name :",inter.name
    print "interface description:",inter.description
    print "interface flags:",inter.flags

pycap.freealldevs(if_list)

#test for list_datlinks
ret,dl=pycap.list_datalinks(handle)
print "ret:",ret
for i in range(ret):
    print "datalink type:",dl[i]
#test for ByteArray
ba=pycap.ByteArray(20)
ba.byte_buffer[0]=1
ba.byte_buffer[1]=2
print ba.byte_buffer[0]
print ba.byte_buffer[1]
#test for loop 

pycap.loop(handle, 2000, cb, "jazy")